package com.media.selector.media.model.entity

import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Parcel
import android.os.Parcelable
import com.media.selector.R
import com.media.selector.media.model.loader.AlbumLoader
import com.media.selector.media.model.loader.BaseCursorLoader

/**
 * 相册 entity
 */
data class AlbumEntity(
    val mId: String,
    val mCoverUri: Uri?,
    val mDisplayName: String,
    var mCount: Long
) : Parcelable {

    constructor(source: Parcel) : this(
        mId = source.readString() ?: "",
        mCoverUri = source.readParcelable<Uri>(Uri::class.java.classLoader),
        mDisplayName = source.readString() ?: "",
        mCount = source.readLong()
    )

    override fun describeContents() = 0

    override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
        writeString(mId)
        writeParcelable(mCoverUri, 0)
        writeString(mDisplayName)
        writeLong(mCount)
    }

    fun isAll(): Boolean = ALBUM_ID_ALL == mId

    fun getDisplayName(context: Context): String? = if (isAll()) context.getString(R.string.media_album_name_all) else mDisplayName

    companion object {

        const val ALBUM_ID_ALL = "-1"
        const val ALBUM_NAME_ALL = "All"

        fun valueOf(cursor: Cursor): AlbumEntity {
            val column = cursor.getString(cursor.getColumnIndex(AlbumLoader.COLUMN_URI))
            return AlbumEntity(
                cursor.getString(cursor.getColumnIndex(BaseCursorLoader.COLUMN_BUCKET_ID)),
                Uri.parse(column ?: ""),
                cursor.getString(cursor.getColumnIndex(BaseCursorLoader.COLUMN_BUCKET_DISPLAY_NAME)),
                cursor.getLong(cursor.getColumnIndex(AlbumLoader.COLUMN_COUNT))
            )
        }

        @JvmField
        val CREATOR: Parcelable.Creator<AlbumEntity> = object : Parcelable.Creator<AlbumEntity> {
            override fun createFromParcel(source: Parcel): AlbumEntity = AlbumEntity(source)
            override fun newArray(size: Int): Array<AlbumEntity?> = arrayOfNulls(size)
        }
    }
}